package com.wnm.web;

import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnm.pojo.Address;
import com.wnm.pojo.User;
import com.wnm.service.AddressService;
import com.wnm.service.impl.AddressServiceImpl;

@WebServlet("/address/*")
public class AddressServlet extends BaseServlet {
	public void showAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
		User user = (User) request.getSession().getAttribute("user");
		AddressService addressService = new AddressServiceImpl();
		List<Address> addresses = addressService.showAddressByUserid(user.getId());
		ObjectMapper om = new ObjectMapper();
		om.writeValue(response.getWriter(), addresses);
	}
	public void setDefault(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String addressid = request.getParameter("id");
		AddressService addressService = new AddressServiceImpl();
		addressService.setDefault(Integer.parseInt(addressid));
	}

	public void addAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
		User user = (User) request.getSession().getAttribute("user");
		Address address = new Address();
		address.setUserid(user.getId());
		address.setAccept(request.getParameter("accept"));
		address.setProvince(request.getParameter("province"));
		address.setCity(request.getParameter("city"));
		address.setArea(request.getParameter("area"));
		address.setAddress(request.getParameter("address"));
		address.setTelphone(request.getParameter("telphone"));
		String type = request.getParameter("type");
		if (type.equals("false")) {
			address.setType("2");
		} else {
			address.setType("1");
		}
		AddressService addressService = new AddressServiceImpl();

		addressService.add(address);
		ObjectMapper om = new ObjectMapper();
		om.writeValue(response.getWriter(), address);
	}

}
